import React, { useState, useEffect, useRef } from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import {
  Card,
  message,
  Tabs,
  Form,
  Input,
  Button,
  Select,
  Checkbox,
  Row,
  Col,
  InputNumber,
  Space,
  Modal,
  Upload,
  Badge,
} from 'antd';
import { connect, FormattedMessage, history,useIntl } from 'umi';
import CateComp from '@/components/CategoryComponent';
import { WhseSelect } from '@/components/FormItemSelect';
import request from '@/utils/request';
import ImgQuick from '@/pages/admin/imgQuick';
import UploadUtil from '@/components/UploadUtil';
import { PlusOutlined, LoadingOutlined } from '@ant-design/icons';

const { TabPane } = Tabs;
const apiURL = '/api/services/app/SysConfig/';
const currentControl = 'SysConfig';

const ViewSysConfig: React.FC<any> = (props) => {
  const [loading, setLoading] = useState(false);
  const [visible, setVisible] = useState(false);
  const [data, setData] = useState<any>({});
  const [fileList, setFileList] = useState<any[]>([]);
  const [ErrBusiness, setErrBusiness] = useState(0);
  const [ErrConfigEmail, setErrConfigEmail] = useState(0);
  const formRef = useRef<any>(null);
  const intl = useIntl();

  useEffect(() => {
    getObj();
  }, []);

  const getObj = () => {
    setLoading(true);
    request(apiURL + 'GetConfig', {
      method: 'GET',
    }).then((response) => {
      if (response.result) {
        const company = response.result;
        const fileList: any = [];
        if (company.logo) {
          const obj = {
            uid: company.logo,
            name: company.logo,
            response: {
              result: company.logo,
            },
            status: 'done',
            url: UploadUtil.getOssFile + company.logo,
          };
          fileList.push(obj);
        }
        if (formRef.current) {
          formRef.current.setFieldsValue({ company });
        }
        setData(company);
        setFileList(fileList);
      } else {
        message.warning(intl.formatMessage({ id: 'pages.noConfig' }));
      }
      setLoading(false);
    });
  };

  const onFinish = (values: any) => {
    setLoading(true);
    const act = values.company.id === 0 || !values.company.id ? 'Abp/create' : 'Abp/update';
    values.company.logo = data.logo;
    props
      .dispatch({
        type: act,
        payload: values.company,
        control: currentControl,
      })
      .then(() => {
        const resp = props.response;
        if (resp.result) {
          message.success(intl.formatMessage({ id: 'pages.save.success' }));
          setData(resp.result);
        }
        setLoading(false);
        setErrBusiness(0);
        setErrConfigEmail(0);
      });
  };

  const clickFun = (val: any) => {
    const fileList = [];
    const obj = {
      uid: val,
      name: val,
      response: {
        result: val,
      },
      status: 'done',
      url: UploadUtil.getOssFile + val,
    };
    fileList.push(obj);
    setData({ ...data, logo: val });
    setFileList(fileList);
    setVisible(false);
  };

  const handleUploadList = (info: any) => {
    if (info.file.status == 'error') {
      message.error(info.file.response.error.message);
    }
    if (info.file.status === 'done') {
      message.success(`${info.file.name} 上传成功`);
    }
    setFileList(info.fileList);
  };

  const onFinishFailed = (errorInfo: any) => {
    let ErrBusiness = 0;
    let ErrConfigEmail = 0;
    const orderRelErr = 0;
    errorInfo.errorFields.forEach((element: any) => {
      if (element.name[1].indexOf('start') > -1) {
        ErrBusiness++;
      } else if (element.name[1].indexOf('smtP_') > -1) {
        ErrConfigEmail++;
      }
      setErrBusiness(ErrBusiness);
      setErrConfigEmail(ErrConfigEmail);
    });
  };

  const layout = {
    labelCol: { span: 5 },
    wrapperCol: { span: 19 },
  };
  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div className="ant-upload-text">
        <FormattedMessage id="pages.upload" />
      </div>
    </div>
  );

  return (
    <PageHeaderWrapper title={false} breadcrumbRender={false} ghost>
      <Form
        {...layout}
        ref={formRef}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
      >
        <Card
          title={<FormattedMessage id="menu.admin.sysconfig" />}
          extra={
            <Space>
              <Button type="primary" htmlType="submit" loading={loading}>
                <span><FormattedMessage id="pages.save" /></span>
              </Button>
              <Button type="primary" onClick={getObj} loading={loading}>
                <span><FormattedMessage id="pages.refresh" /></span>
              </Button>
            </Space>
          }
          actions={[
            <Button type="primary" danger onClick={() => history.push('/InitWizard')}>
              <FormattedMessage id="pages.system.init" />
            </Button>,
          ]}
        >
          <Tabs defaultActiveKey="1">
            <TabPane tab={<FormattedMessage id="pages.configOverall" />} key="1">
              <Row gutter={[16, 16]}>
                <Col span={12}>
                  <Form.Item name={['company', 'id']} label="ID" hidden>
                    <Input disabled style={{ width: 50 }} />
                  </Form.Item>
                  <Form.Item
                    name={['company', 'companyName']}
                    label={<FormattedMessage id="pages.company.name" />}
                    rules={[
                      {
                        required: true,
                        message: <FormattedMessage id="pages.company.name.required" />,
                      },
                    ]}
                  >
                    <Input style={{ width: 200 }} />
                  </Form.Item>
                  <Form.Item
                    name={['company', 'address']}
                    label={<FormattedMessage id="pages.address" />}
                  >
                    <Input />
                  </Form.Item>
                  <Form.Item
                    name={['company', 'telphone']}
                    label={<FormattedMessage id="pages.telphone" />}
                  >
                    <Input style={{ width: 200 }} />
                  </Form.Item>
                  <Form.Item name={['company', 'email']} label={<FormattedMessage id="pages.email" />}>
                    <Input style={{ width: 200 }} />
                  </Form.Item>
                  <Form.Item name={['company', 'fax']} label={<FormattedMessage id="pages.fax" />}>
                    <Input style={{ width: 200 }} />
                  </Form.Item>

                  <Form.Item label={<FormattedMessage id="pages.logo" />}>
                    <Input.Group compact>
                      <Form.Item>
                        <Upload
                          action={UploadUtil.uploadOSS}
                          headers={{
                            Authorization: UploadUtil.accessToken,
                          }}
                          data={{
                            objectId: data?.id,
                            objectName: 'SysConfig',
                            objectField: 'logo',
                          }}
                          listType="picture-card"
                          fileList={fileList}
                          multiple={true}
                          onChange={handleUploadList}
                        >
                          {fileList.length >= 1 ? null : uploadButton}
                        </Upload>
                      </Form.Item>
                      <Form.Item>
                        <Button onClick={() => setVisible(true)}>
                          {<FormattedMessage id="pages.Picture.Select" />}
                        </Button>
                      </Form.Item>
                    </Input.Group>
                  </Form.Item>
                </Col>
              </Row>
            </TabPane>
            <TabPane tab={<FormattedMessage id="pages.configFinance" />} key="2">
              <Row>
                <Col span={12}>
                  <Form.Item name={['company', 'costMethod']} label={<FormattedMessage id="pages.costMethod" />}>
                    <Select style={{ width: 200 }} placeholder={intl.formatMessage({ id: 'pages.costMethod' })}>
                      <Select.Option key="A" value="A">
                        <FormattedMessage id="pages.Average" />
                      </Select.Option>
                      <Select.Option key="F" value="F">
                        <FormattedMessage id="pages.FIFO" />
                      </Select.Option>
                      <Select.Option key="L" value="L">
                        <FormattedMessage id="pages.Last" />
                      </Select.Option>
                    </Select>
                  </Form.Item>
                  <CateComp
                    layout="currency"
                    width={200}
                    name={['company', 'baseCurrCode']}
                    label={<FormattedMessage id="pages.currency" />}
                  />
                  <CateComp
                    layout="taxRegion"
                    width={200}
                    name={['company', 'taxRegionCode']}
                    label={<FormattedMessage id="pages.taxRegion" />}
                  />
                  <Form.Item
                    name={['company', 'decimalsCost']}
                    label={<FormattedMessage id="pages.decimalsCost" />}
                  >
                    <InputNumber min={0} max={18} />
                  </Form.Item>
                  <Form.Item
                    name={['company', 'decimalsPrice']}
                    label={<FormattedMessage id="pages.decimalsPrice" />}
                  >
                    <InputNumber min={0} max={18} />
                  </Form.Item>
                  <Form.Item
                    name={['company', 'decimalsGeneral']}
                    label={<FormattedMessage id="pages.decimalsGeneral" />}
                  >
                    <InputNumber min={0} max={18} />
                  </Form.Item>
                </Col>
              </Row>
            </TabPane>
            <TabPane
              tab={
                <Badge count={ErrBusiness}>
                  <FormattedMessage id="pages.configBusiness" />
                </Badge>
              }
              key="3"
            >
              <Row gutter={16}>
                <Col span={12}>
                  <Form.Item
                    name={['company', 'startOrderNum']}
                    label={<FormattedMessage id="pages.startOrderNum" />}
                    rules={[
                      {
                        required: true,
                        message: <FormattedMessage id="pages.startOrderNum.required" />,
                      },
                    ]}
                  >
                    <Input style={{ width: 200 }} />
                  </Form.Item>
                  <Form.Item
                    name={['company', 'enableSoMsg']}
                    label={<FormattedMessage id="pages.enableSoMsg" />}
                    valuePropName="checked"
                  >
                    <Checkbox
                      onChange={(e) => {
                        data.enableSoMsg = e.target.checked;
                        setData(data);
                      }}
                    />
                  </Form.Item>
                  <Form.Item name={['company', 'soMsgTemplate']} label={<FormattedMessage id="pages.soMsgTemplate" />}>
                    <Input disabled={!data.enableSoMsg} />
                  </Form.Item>
                  <Form.Item name={['company', 'jobNumPre']} label={<FormattedMessage id="pages.jobNumPre" />}>
                    <Input />
                  </Form.Item>
                  <Form.Item
                    name={['company', 'startJobNum']}
                    label={<FormattedMessage id="pages.startJobNum" />}
                    rules={[
                      {
                        required: true,
                        message: <FormattedMessage id="pages.startJobNum.required" />,
                      },
                    ]}
                  >
                    <InputNumber min={1000} />
                  </Form.Item>
                  <Form.Item
                    name={['company', 'enableRcvMsg']}
                    label={<FormattedMessage id="pages.enableRcvMsg" />}
                    valuePropName="checked"
                  >
                    <Checkbox
                      onChange={(e) => {
                        data.enableRcvMsg = e.target.checked;
                        setData(data);
                      }}
                    />
                  </Form.Item>
                  <Form.Item name={['company', 'rcvMsgTemplate']} label={<FormattedMessage id="pages.rcvMsgTemplate" />}>
                    <Input disabled={!data.enableRcvMsg} />
                  </Form.Item>
                  <Form.Item name={['company', 'maxMRPTask']} label={<FormattedMessage id="pages.maxMRPTask" />}>
                    <InputNumber min={1} max={99} />
                  </Form.Item>
                </Col>
                <Col span={12}>
                  <Form.Item
                    name={['company', 'startPONum']}
                    label={<FormattedMessage id="pages.startPONum" />}
                    rules={[
                      {
                        required: true,
                        message: <FormattedMessage id="pages.startPONum.required" />,
                      },
                    ]}
                  >
                    <Input style={{ width: 200 }} />
                  </Form.Item>
                  <Form.Item
                    name={['company', 'enableSugg']}
                    label={<FormattedMessage id="pages.enableSugg" />}
                    valuePropName="checked"
                  >
                    <Checkbox
                      onChange={(e) => {
                        data.enableSugg = e.target.checked;
                        setData(data);
                      }}
                    />
                  </Form.Item>
                  <Form.Item name={['company', 'suggMsgTemplate']} label={<FormattedMessage id="pages.suggMsgTemplate" />}>
                    <Input disabled={!data.enableSugg} />
                  </Form.Item>
                  <Form.Item name={['company', 'poAprvAmt']} label={<FormattedMessage id="pages.poAprvAmt" />}>
                    <InputNumber min={0} />
                  </Form.Item>
                  <Form.Item label={<FormattedMessage id="pages.defInspWhse" />} style={{ marginBottom: 0 }}>
                    <Input.Group compact>
                      <WhseSelect
                        width={200}
                        showSearch={false}
                        name={['company', 'defInspWhse']}
                        placeholder={intl.formatMessage({ id: 'pages.warehouse' })}
                      />
                      <Form.Item name={['company', 'defInspBin']}>
                        <Input placeholder={intl.formatMessage({ id: 'pages.binNum' })} />
                      </Form.Item>
                    </Input.Group>
                  </Form.Item>
                  <Form.Item label={<FormattedMessage id="pages.defaultWhse" />} style={{ marginBottom: 0 }}>
                    <Input.Group compact>
                      <WhseSelect
                        width={200}
                        showSearch={false}
                        name={['company', 'defaultWhse']}
                      />
                      <Form.Item name={['company', 'defaultBin']}>
                        <Input placeholder={intl.formatMessage({ id: 'pages.binNum' })} />
                      </Form.Item>
                    </Input.Group>
                  </Form.Item>
                  <Form.Item label={<FormattedMessage id="pages.defRcvWhse" />} style={{ marginBottom: 0 }}>
                    <Input.Group compact>
                      <WhseSelect
                        width={200}
                        showSearch={false}
                        name={['company', 'defRcvWhse']}
                        placeholder={intl.formatMessage({ id: 'pages.warehouse' })}
                      />
                      <Form.Item name={['company', 'defaultRcvBin']}>
                        <Input placeholder={intl.formatMessage({ id: 'pages.binNum' })} />
                      </Form.Item>
                    </Input.Group>
                  </Form.Item>
                  <Form.Item label={<FormattedMessage id="pages.defShipWhse" />} style={{ marginBottom: 0 }}>
                    <Input.Group compact>
                      <WhseSelect
                        width={200}
                        showSearch={false}
                        name={['company', 'defShipWhse']}
                        placeholder={intl.formatMessage({ id: 'pages.warehouse' })}
                      />
                      <Form.Item name={['company', 'defShipBin']}>
                        <Input placeholder={intl.formatMessage({ id: 'pages.binNum' })} />
                      </Form.Item>
                    </Input.Group>
                  </Form.Item>
                </Col>
              </Row>
            </TabPane>
            <TabPane tab={<FormattedMessage id="pages.configWeixin" />} key="5">
              <Row>
                <Col span={12}>
                  <Form.Item name={['company', 'wxAppID']} label={<FormattedMessage id="pages.wxAppID" />}>
                    <Input />
                  </Form.Item>
                  <Form.Item name={['company', 'wxAppSecret']} label={<FormattedMessage id="pages.wxAppSecret" />}>
                    <Input />
                  </Form.Item>
                </Col>
                <Col span={12}></Col>
              </Row>
            </TabPane>
            <TabPane
              tab={
                <Badge count={ErrConfigEmail}>
                  <FormattedMessage id="pages.sysConfig" />
                </Badge>
              }
              key="6"
            >
              <Row>
                <Col span={12}>
                  <Form.Item
                    name={['company', 'smtP_Server']}
                    label={<FormattedMessage id="pages.smtp.server" />}
                    rules={[
                      {
                        required: true,
                        message: <FormattedMessage id="pages.smtp.server.required" />,
                      },
                    ]}
                  >
                    <Input />
                  </Form.Item>
                  <Form.Item name={['company', 'smtP_Port']} label={<FormattedMessage id="pages.smtp.port" />}>
                    <Input />
                  </Form.Item>
                  <Form.Item name={['company', 'smtP_User']} label={<FormattedMessage id="pages.smtp.user" />}>
                    <Input />
                  </Form.Item>
                  <Form.Item name={['company', 'smtP_Password']} label={<FormattedMessage id="pages.smtp.password" />}>
                    <Input.Password />
                  </Form.Item>
                  <Form.Item
                    name={['company', 'osS_Capacity']}
                    label={<FormattedMessage id="pages.ossCapacity" />}
                  >
                    <InputNumber disabled addonAfter="GB" />
                  </Form.Item>
                  <Form.Item
                    name={['company', 'smS_TotalNum']}
                    label={<FormattedMessage id="pages.smsTotalNum" />}
                  >
                    <InputNumber disabled addonAfter={intl.formatMessage({id: 'pages.PCS'})} />
                  </Form.Item>
                </Col>
                <Col span={12}></Col>
              </Row>
            </TabPane>
          </Tabs>
        </Card>
      </Form>
      <Modal
        title={<FormattedMessage id="pages.Picture.Select" />}
        visible={visible}
        destroyOnClose={true}
        onCancel={() => setVisible(false)}
        width={750}
        footer={false}
      >
        <ImgQuick clickFun={(val: any) => clickFun(val)} ext=".jpg,.jpeg,.png,.gif" />
      </Modal>
    </PageHeaderWrapper>
  );
};

export default connect(({ Abp }: API.IConnectState) => ({
  response: Abp.response,
  currentUser: Abp.currentUser,
}))(ViewSysConfig);
